package com.sibbay.syncbox;

import com.sibbay.syncbox.adapter.MediaScannerThread;
import com.sibbay.syncbox.syncdb.SyncDatabase;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

public class MediaScannerService extends Service {

	private MediaScannerThread mMediaScannerThread;
	
	@Override
	public void onCreate() {
		mMediaScannerThread = new MediaScannerThread(SyncDatabase.getInstance(getApplicationContext()));
		mMediaScannerThread.setOnUpdate(new Runnable() {
			public void run() {
				//
			}
		});
		Scheduler.start(getApplicationContext());
	};
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);

		mMediaScannerThread.rescan();
		
		return START_NOT_STICKY;
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	///
	
	private static final class Scheduler {

		private static final int TIME_INTERVAL = 15 * 60 * 1000; 	// 15 min
		
		static void start(final Context context) {
			final PendingIntent operation = getOperation(context);
			final AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
			am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), TIME_INTERVAL, operation);
		}
		
//		static void stop(final Context context) {
//			final PendingIntent operation = getOperation(context);
//			final AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//			am.cancel(operation);
//		}
//		
		private static PendingIntent getOperation(final Context context) {
			final Intent intent = new Intent();
			intent.setClass(context, MediaScannerService.class);
			return PendingIntent.getService(context, 0, intent, 0);
		}
	}
}
